<?php

class AdminLogin extends Security {
    private static $allowed_actions = array(
    	'login',
        'LoginForm'
    );
	
	/**
	 * Show the "login" page
	 *
	 * @return string Returns the "login" page as HTML code.
	 */
	public function login() {
		Requirements::themedCSS('AdminLogin');

		// Get response handler
		$controller = $this->getResponseController(_t('AdminLogin.LOGIN', 'Administrator Log In'));

		// if the controller calls Director::redirect(), this will break early
		if(($response = $controller->getResponse()) && $response->isFinished()) return $response;

		$form = $this->LoginForm();
		if(Session::get('AdminLogin.force_message')){
			$form->sessionMessage(Session::get('AdminLogin.force_message'), 'warning', false);
			Session::set('AdminLoginForm.force_message',1);
			Session::clear('AdminLogin.force_message');
		}
		$content = $form->forTemplate();
		
		if($message = $this->getLoginMessage()) {
			$customisedController = $controller->customise(array(
				"Content" => $message,
				"Form" => $content,
			));
		} else {
			$customisedController = $controller->customise(array(
				"Form" => $content,
			));
		}
		
		Session::clear('Security.Message');

		// custom processing
		return $customisedController->renderWith($this->getTemplatesFor('admin_login'));
	}

	/**
	 * Get a link to a security action
	 *
	 * @param string $action Name of the action
	 * @return string Returns the link to the given action
	 */
	public function Link($action = null) {
		return Controller::join_links(Director::baseURL(), "administrator", $action);
	}
    
    function LoginForm(){
        return AdminAuthenticator::get_login_form($this);
    }
	
	/**
	 * Prepare the controller for handling the response to this request
	 *
	 * @param string $title Title to use
	 * @return Controller
	 */
	protected function getResponseController($title) {
		if(!class_exists('SiteTree')) return $this;

		// Use sitetree pages to render the security page
		$tmpPage = new Page();
		$tmpPage->Title = $title;
		$tmpPage->URLSegment = "administrator";
		// Disable ID-based caching  of the log-in page by making it a random number
		$tmpPage->ID = -1 * rand(1,10000000);

		$controller = Page_Controller::create($tmpPage);
		$controller->setDataModel($this->model);
		$controller->init();
		return $controller;
	}
}
